<template>
  <div class="content" ref="contentContainer">
    <!-- 下拉刷新提示 -->
    <div ref="refreshIndicator" class="refresh-indicator">
      {{ isRefreshing ? '刷新中...' : '下拉刷新' }}
    </div>
    
    <!-- 动态标题 -->
    <h3 v-if="haveFollow === '0'">作品推荐</h3>
    <h3 v-else-if="haveFollow === '1'">关注列表</h3>
    <h3 v-else>未知状态</h3>

    <!-- 新通知提示 -->
    <div 
      v-if="unreadNotifications > 0" 
      class="notification-badge"
      @click="showAllNotifications = true"
    >
      你有 {{ unreadNotifications }} 条新动态
    </div>

    <!-- 通知列表 -->
    <div class="notifications-panel" :class="{ 'show': showAllNotifications }">
      <div class="notifications-header">
        <h4>关注动态通知</h4>
        <button class="close-btn" @click="showAllNotifications = false">×</button>
      </div>
      <div class="notification-item" v-for="(item, index) in notifications" :key="index">
        <p>
          <span class="username">{{ item.authorName }}</span>
          发布了新内容: {{ item.title }}
        </p>
        <span class="time">{{ formatTime(item.time) }}</span>
        <button 
          class="view-btn" 
          @click="goToContent(item.contentId); showAllNotifications = false"
        >
          查看
        </button>
      </div>
      <button 
        v-if="notifications.length" 
        class="mark-all-read" 
        @click="markAllAsRead"
      >
        全部标为已读
      </button>
    </div>

    <!-- 动态列表 -->
    <div 
      class="post-list" 
      @touchstart="handleTouchStart" 
      @touchmove="handleTouchMove" 
      @touchend="handleTouchEnd"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
      ref="scrollContainer"
    >
      <!-- 列表项 -->
      <div 
        class="post-item" 
        v-for="(post, index) in posts" 
        :key="post.id || `post_${index}`"  
      >
        <div >
          <!-- 用户信息 + 关注按钮 -->
          <div class="user-info">
            <div class="user-avatar-name">
              <img 
                :src="post.user.avatar || defaultAvatar" 
                alt="用户头像" 
                class="avatar"
                @error="handleImageError"
              />
              <span class="username">{{ post.user.username }}</span>
            </div>
            
            <div v-if="!admin || post.userId !== admin.id" class="follow-btn-container">
              <button 
                class="follow-btn" 
                v-if="!isUserFollowed(post.userId)" 
                @click="handleFollow(post.userId, admin?.id)"
                :disabled="isFollowing[post.userId]"
              >
                {{ isFollowing[post.userId] ? '关注中...' : '关注' }}
              </button>
              <button 
                class="followed-btn" 
                v-else 
                @click="handleUnfollow(post.userId, admin?.id)"
                :disabled="isFollowing[post.userId]"
              >
                {{ isFollowing[post.userId] ? '取消中...' : '已关注' }}
              </button>
            </div>
          </div>
       
          <!-- 动态内容 -->
          <div class="post-content">
            <router-link 
              :to="{ 
                path: '/follow-detail',  
                query: { id: post.id }  
              }"
              class="router-link-style"  
            >
              <p class="content-text">{{ post.content }}</p>
            </router-link>
            
            <!-- 图片容器 -->
            <div class="images-container" v-if="post.images && post.images.length">
              <img 
                v-for="(imgPath, idx) in post.images.split(',').filter(path => path.trim())" 
                :key="idx"
                :src="imgPath" 
                alt="帖子图片" 
                class="post-image"
                @error="(e) => handleImageError(e, idx)"  
                loading="lazy" 
              >
            </div>
          </div>

          <!-- 互动按钮 -->
          <div class="interaction-buttons">
            <button class="like-btn" @click="addLikeCount(post)">👍 {{ post.likeCount }}</button>
            <button class="comment-btn" @click="focusCommentInput(post.id)">💬 评论</button>
          </div>

          <!-- 评论框 -->
          <div class="comment-box" v-if="admin" @click="focusCommentInput(post.id)">
            <img 
              :src="admin.avatar || defaultAvatar" 
              alt="登录用户头像" 
              class="comment-avatar"
            />
            <input 
              type="text" 
              placeholder="添加评论..." 
              class="comment-input"
              :ref="(el) => commentInputs[post.id || `post_${index}`] = el"
              @keydown.enter.prevent="addComment(post)"
            >
          </div>

          <!-- 发布时间 -->
          <div class="post-time">{{ formatTime(post.createTime) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import api from '@/api' 
import router from '@/router';
import { connectWebSocket, disconnectWebSocket } from '@/util/socket.js';

// 类型定义
interface Post {
  id?: string;
  userId: number;
  user: { username: string; avatar?: string; id?: number };
  title: string;
  content: string;
  updateTime: number; 
  createTime: number;
  likeCount: number;
  images?: string;
  comments?: any[];
}

// 通知类型定义
interface Notification {
  id?: number;
  authorId: number;
  authorName: string;
  title: string;
  contentId: string;
  time: number;
  isRead: boolean;
}

// 状态管理
const loginStatus = ref('0')
const haveFollow: Ref<string> = ref('0') 
const posts: Ref<Post[]> = ref([])
const isFollowing: Ref<Record<number, boolean>> = ref({}) 
const admin = JSON.parse(localStorage.getItem("admin") || 'null')
const uids = ref<number[]>([])
// 评论相关
const commentInputs = ref<Record<string, HTMLInputElement | null>>({})

// 推送通知相关
const notifications = ref<Notification[]>([])
const unreadNotifications = ref(0)
const showAllNotifications = ref(false)
let notificationSound: HTMLAudioElement | null = null;

// 下拉刷新相关
const scrollContainer = ref<HTMLDivElement | null>(null)
const contentContainer = ref<HTMLDivElement | null>(null)
const refreshIndicator = ref<HTMLDivElement | null>(null)
const startY = ref(0)
const currentY = ref(0)
const refreshOffset = ref(0)
const isDragging = ref(false)
const isRefreshing = ref(false)
const refreshThreshold = 60 // 触发刷新的阈值

// 默认头像
const defaultAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.zkgnSpOw7PiuiMYOWpGfawHaGL?w=240&h=211&c=8&rs=1&qlt=90&o=6&cb=thwsc5&dpr=2.3&pid=3.1&rm=2'

// 生命周期：初始化
onMounted(() => {
  if (admin) loginStatus.value = '1'
  checkLoginStatus()
  
  // 初始隐藏下拉刷新
  nextTick(() => {
    if (refreshIndicator.value) {
      refreshIndicator.value.style.transform = 'translateY(-100%)';
    }
  })
  
  // 初始化通知音效
  notificationSound = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3');

  // 连接WebSocket并监听通知
  if (admin) {
    connectWebSocket();
    setupNotificationListener();
    loadHistoricalNotifications();
  }
})

// 组件卸载时清理
onUnmounted(() => {
  disconnectWebSocket();
  window.removeEventListener('newNotification', handleNewNotification);
})

// 监听关注列表变化
watch(uids, (newVal) => {
  haveFollow.value = newVal.length > 0 ? '1' : '0'
})

// 设置通知监听器
const setupNotificationListener = () => {
  window.addEventListener('newNotification', (e: any) => {
    handleNewNotification(e.detail);
  });
}

// 处理新通知
const handleNewNotification = (notification: Notification) => {
  // 添加到通知列表
  notifications.value.unshift({...notification, isRead: false});
  
  // 更新未读计数
  unreadNotifications.value++;
  
  // 播放通知音效
  if (notificationSound) {
    notificationSound.volume = 0.3;
    notificationSound.play().catch(e => console.log('无法播放通知音效:', e));
  }
  
  // 显示通知提示动画
  showNotificationToast(notification);
}

// 显示通知提示
const showNotificationToast = (notification: Notification) => {
  const toast = document.createElement('div');
  toast.className = 'notification-toast';
  toast.innerHTML = `
    <p><strong>${notification.authorName}</strong> 发布了新内容</p>
    <p>${notification.title}</p>
  `;
  document.body.appendChild(toast);
  
  // 显示动画
  setTimeout(() => toast.classList.add('show'), 10);
  
  // 点击查看
  toast.addEventListener('click', () => {
    goToContent(notification.contentId);
    document.body.removeChild(toast);
    markAsRead(notification);
  });
  
  // 自动消失
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => document.body.removeChild(toast), 300);
  }, 5000);
}

// 加载历史通知
const loadHistoricalNotifications = async () => {
  try {
    const res = await api.getReq(`/notifications?userId=${admin.id}`);
    if (res.data.code === 1) {
      notifications.value = res.data.data || [];
      console.log(res.data.data)
      // 计算未读数量
      unreadNotifications.value = notifications.value.filter(n => !n.isRead).length;
    }
  } catch (error) {
    console.error('加载历史通知失败:', error);
  }
}

// 标记单个通知为已读
const markAsRead = async (notification: Notification) => {
  try {
    if (notification.id) {
      await api.postReq(`/notifications/read`, notification.id);
    }
    notification.isRead = true;
    unreadNotifications.value = notifications.value.filter(n => !n.isRead).length;
  } catch (error) {
    console.error('标记通知为已读失败:', error);
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  if (!admin?.id) { // 先校验 userId 是否存在
    console.log(admin)
    console.error('用户ID不存在，无法标记全部已读');
    return;
  }
  try {
    await api.postReq(`/notifications/readAll?userId=${admin?.id}`);
    notifications.value.forEach(n => n.isRead = true);
    unreadNotifications.value = 0;
  } catch (error) {
    // 打印后端返回的具体错误提示
    console.error('后端错误信息:', error);
  }
}

// 跳转到内容详情
const goToContent = (contentId: string) => {
  router.push(`/follow-detail?id=${contentId}`);
}

// 刷新页面逻辑
const refreshPage = () => {
  if (isRefreshing.value) return;
  
  isRefreshing.value = true;
  if (refreshIndicator.value) {
    refreshIndicator.value.textContent = '刷新中...';
    refreshIndicator.value.style.transform = 'translateY(0)';
  }
  
  checkLoginStatus()
    .finally(() => {
      isRefreshing.value = false;
      refreshOffset.value = 0;
      if (refreshIndicator.value) {
        refreshIndicator.value.textContent = '下拉刷新';
        refreshIndicator.value.style.transform = 'translateY(-100%)';
      }
    });
}

// 点赞逻辑
const addLikeCount = (p: Post) => {
  const like = {
    userId: admin?.id || null,
    likedType: true,
    likedId: p.id  
  };
  if (!like.userId) {
    router.push('/login')
  } else {
    api.postReq('/post/addLikeCount', like).then(res => {
      const result = res.data
      if (result.code === 1 || result.code === 2) {
        p.likeCount = result.data
        console.log(result.msg)
      } else {
        console.log(result.msg)
      }
    })  
  }
}

// 检查登录状态
const checkLoginStatus = async () => {
  try {
    if (loginStatus.value === '1' && admin) {
      await getAllFollowedIds(admin.id)
    } else {
      await getPublicPosts()
    }
  } catch (error) {
    console.error('初始化检查异常：', error);
  }
}

// 检查用户是否被关注
const isUserFollowed = (userId: number): boolean => {
  return uids.value.includes(userId)
}

// 获取关注用户的 ID 列表
const getAllFollowedIds = async (id: number) => {
  try {
    const res = await api.postReq('/userFollow/getAllFollowedId?id=' + id)
    const result = res.data
    uids.value = result.data || []
    if (uids.value.length > 0) {
      await getFollowedPosts()
    } else {
      haveFollow.value = '0'
      await getPublicPosts()
    }
  } catch (error) {
    console.error('获取关注列表失败：', error)
    haveFollow.value = '0'
    await getPublicPosts()
  }
}

// 获取公开帖子
const getPublicPosts = async () => {
  haveFollow.value = '0'
  try {
    const res = await api.postReq('/post/selectAll')
    const result = res.data
    posts.value = result.data || []
  } catch (error) {
    console.error('获取公开动态失败：', error)
  }
}

// 获取关注用户的帖子
const getFollowedPosts = async () => {
  haveFollow.value = '1'
  try {
    const res = await api.postReq('/post/selectByUid', uids.value)
    const result = res.data
    posts.value = result.data || []
  } catch (error) {
    console.error('获取关注动态失败：', error)
  }
}

// 关注用户
const handleFollow = (followedId: number, followerId: number | undefined) => {
  if (!followerId || loginStatus.value === '0' || isFollowing.value[followedId]) return;

  isFollowing.value[followedId] = true;
  
  api.postReq('/userFollow/add', { followedId, followerId })
    .then(res => {
      if (res.data.code === 1) {
        if (!uids.value.includes(followedId)) {
          uids.value = [...uids.value, followedId]
        }
        console.log('关注成功，现在可以接收该用户的动态推送')
      }
    })
    .catch(error => console.error('关注操作失败：', error))
    .finally(() => {
      isFollowing.value[followedId] = false;
    });
}

// 取消关注
const handleUnfollow = (followedId: number, followerId: number | undefined) => {
  if (!followerId || isFollowing.value[followedId]) return;

  isFollowing.value[followedId] = true;
  
  api.postReq('/userFollow/del', { followedId, followerId })
    .then(res => {
      if (res.data.code === 1) {
        uids.value = uids.value.filter(id => id !== followedId)
        console.log('取消关注成功，将不再接收该用户的动态推送')
      }
    })
    .catch(error => console.error('取消关注失败：', error))
    .finally(() => {
      isFollowing.value[followedId] = false;
    });
}

// 处理图片加载错误
const handleImageError = (e: Event, idx?: number) => {
  const img = e.target as HTMLImageElement
  if (img.src !== defaultAvatar) {
    img.src = defaultAvatar;
    img.style.opacity = '0.6';
  }
}

// 时间格式化
const formatTime = (updateTime: number): string => {
  const date = new Date(updateTime);
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

// 数字补零
const padZero = (num: number): string => num.toString().padStart(2, '0');

// 下拉刷新：移动端触摸事件
const handleTouchStart = (e: TouchEvent) => {
  if (scrollContainer.value && scrollContainer.value.scrollTop <= 0) {
    startY.value = e.touches[0].clientY;
    isDragging.value = true;
  }
}

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value || isRefreshing.value) return;

  currentY.value = e.touches[0].clientY;
  const diff = currentY.value - startY.value;

  if (diff > 0) {
    refreshOffset.value = Math.min(diff / 2, refreshThreshold + 20);
    if (refreshIndicator.value) {
      refreshIndicator.value.style.transform = `translateY(${refreshOffset.value}px)`;
    }
    if (e.cancelable) e.preventDefault();
  }
}

const handleTouchEnd = () => {
  if (!isDragging.value || isRefreshing.value) return;

  isDragging.value = false;

  if (refreshOffset.value >= refreshThreshold) {
    refreshPage();
  } else {
    if (refreshIndicator.value) {
      refreshIndicator.value.style.transform = 'translateY(-100%)';
    }
    refreshOffset.value = 0;
  }
}

// 下拉刷新：桌面端鼠标事件
const handleMouseDown = (e: MouseEvent) => {
  if (scrollContainer.value && scrollContainer.value.scrollTop <= 0) {
    startY.value = e.clientY;
    isDragging.value = true;
  }
}

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value || isRefreshing.value) return;

  currentY.value = e.clientY;
  const diff = currentY.value - startY.value;

  if (diff > 0) {
    refreshOffset.value = Math.min(diff / 2, refreshThreshold + 20);
    if (refreshIndicator.value) {
      refreshIndicator.value.style.transform = `translateY(${refreshOffset.value}px)`;
    }
    if (e.cancelable) e.preventDefault();
  }
}

const handleMouseUp = () => {
  if (!isDragging.value || isRefreshing.value) return;

  isDragging.value = false;

  if (refreshOffset.value >= refreshThreshold) {
    refreshPage();
  } else {
    if (refreshIndicator.value) {
      refreshIndicator.value.style.transform = 'translateY(-100%)';
    }
    refreshOffset.value = 0;
  }
}

// 评论相关方法
const focusCommentInput = (postId?: string) => {
  if (!postId) return;
  
  const input = commentInputs.value[postId];
  if (input) {
    input.focus();
    input.style.borderColor = '#1890ff';
    input.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
    input.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }
}

// 添加评论函数
const addComment = (post: Post) => {
  if (!admin || !post.id) return;
  
  const input = commentInputs.value[post.id];
  if (!input || !input.value.trim()) return;
  
  const commentContent = input.value.trim();
  
  api.postReq('/comment/addComment', {
    targetType:1,
    targetId: post.id,
    userId: admin.id,
    content: commentContent
  })
  .then(res => {
    const result = res.data;
    if (result.code === 1) {
      console.log('评论添加成功');
      input.value = '';
      input.style.borderColor = '';
      input.style.boxShadow = '';
      if (!post.comments) post.comments = [];
      post.comments.push({
        id: Date.now().toString(),
        userId: admin.id,
        username: admin.username,
        avatar: admin.avatar,
        content: commentContent,
        createTime: Date.now()
      });
    } else {
      console.log('评论失败:', result.msg);
    }
  })
  .catch(error => {
    console.error('评论请求失败:', error);
  });
}
</script>

<style scoped>
/* 清除 router-link 默认样式 */
.router-link-style {
  text-decoration: none;
  color: inherit;
  display: block;
}

.content {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

/* 下拉刷新指示器 */
.refresh-indicator {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
  transition: transform 0.3s ease;
  transform: translateY(-100%);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

/* 通知提示 */
.notification-badge {
  background-color: #ff4d4f;
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  margin: 10px 0;
  font-size: 14px;
  cursor: pointer;
  text-align: center;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

/* 通知面板 */
.notifications-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 300px;
  height: 100vh;
  background-color: white;
  box-shadow: -2px 0 10px rgba(0,0,0,0.1);
  z-index: 100;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  overflow-y: auto;
}

.notifications-panel.show {
  transform: translateX(0);
}

.notifications-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.notification-item {
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  flex-direction: column;
}

.notification-item .username {
  font-weight: bold;
  color: #1890ff;
}

.notification-item .time {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
}

.notification-item .view-btn {
  align-self: flex-end;
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 4px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-top: 5px;
}

.mark-all-read {
  width: 100%;
  padding: 10px;
  background-color: #f5f5f5;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

.mark-all-read:hover {
  background-color: #eee;
}

/* 通知提示框 */
.notification-toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(100px);
  background-color: white;
  border-left: 4px solid #1890ff;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  padding: 10px 15px;
  border-radius: 4px;
  z-index: 1000;
  max-width: 300px;
  transition: transform 0.3s ease;
}

.notification-toast.show {
  transform: translateX(-50%) translateY(0);
}

.notification-toast p {
  margin: 5px 0;
  font-size: 14px;
}

.post-list {
  margin-top: 20px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
  scroll-behavior: smooth;
  position: relative;
}

/* 帖子项 */
.post-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

/* 用户信息区域布局 */
.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar-name {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.username {
  font-weight: bold;
  font-size: 15px;
}

/* 关注按钮样式 */
.follow-btn-container {
  margin-left: auto;
}

.follow-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 5px 12px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.follow-btn:disabled {
  background-color: #ff8a80;
  cursor: not-allowed;
}

.followed-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 5px 12px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.followed-btn:disabled {
  background-color: #096dd9;
  cursor: not-allowed;
}

/* 帖子内容区域 */
.post-content {
  margin-bottom: 15px;
}

.content-text {
  margin: 0 0 10px 0;
  text-align: left;
  line-height: 1.6;
}

/* 图片容器 */
.images-container {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.post-image {
  max-width: calc(50% - 4px);
  max-height: 150px;
  border-radius: 4px;
  object-fit: cover;
}

/* 互动按钮区域 */
.interaction-buttons {
  display: flex;
  gap: 15px;
  margin: 12px 0;
}

.like-btn, .comment-btn {
  background: none;
  border: none;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.like-btn:hover, .comment-btn:hover {
  background-color: #f5f5f5;
}

/* 评论框区域 */
.comment-box {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0 15px 0;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
  cursor: text;
}

.comment-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
  transition: all 0.2s;
}

.comment-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 时间样式 */
.post-time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: left;
}
</style>
